package cn.gdcp.listview2;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;

public class StuAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<Student> studentArrayList;
    private IOnDelListener listener;

    public  StuAdapter(Context context,ArrayList<Student> studentArrayList,
                       IOnDelListener listener){
        this.context=context;
        this.studentArrayList=studentArrayList;
        this.listener=listener;
    }

    public void changeData(ArrayList<Student> studentArrayList){
        this.studentArrayList=studentArrayList;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return studentArrayList.size();
    }

    @Override
    public Object getItem(int i) {
        return studentArrayList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }
    int count=0;
    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        Log.e("StuAdapter","getview"+i+"count="+count);
        if(view==null){
            count++;
            LayoutInflater layoutInflater=LayoutInflater.from(context);
            view=layoutInflater.inflate(R.layout.my_list_item,viewGroup,false);
            StuViewHolder holder=new StuViewHolder();
            holder.headImg=view.findViewById(R.id.stu_img);
            holder.nameView=view.findViewById(R.id.stu_name);
            holder.ageView=view.findViewById(R.id.stu_age);
            holder.delView=view.findViewById(R.id.del_img);
            final  View finalView=view;
            view.setTag(holder);
        }
        Student stu=studentArrayList.get(i);
        StuViewHolder holder=(StuViewHolder) view.getTag();

        holder.headImg.setImageResource(stu.getImgId());
        holder.ageView.setText(String.valueOf(stu.getAge()));
        holder.nameView.setText(stu.getName());

        //删除
        holder.delView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //让监听者删除第i个学生
                //点击了删除图标后，先传到这里，再传到MainActivity中的del方法中去
                listener.del(i);
            }
        });

        return view;
    }
}
